#!/usr/bin/env bash

#基准目录
base_dir=~

#站点名称
site_name=ctc-docker

#ctc-docker目录
ctc_docker_dir=${base_dir}/${site_name}

#ctc 应用目录
ctc_html_dir=${ctc_docker_dir}/html/ctc

#ctc-docker备份文件
ctc_docker_tar=${base_dir}/${site_name}.tar.gz

#普通信息输出
normal_print() {
  echo -e "\033[34m \n $1 \n \033[0m"
}

#成功信息输出
success_print() {
  echo -e "\033[32m \n $1 \n \033[0m"
}

#失败信息输出
error_print() {
  echo -e "\033[31m \n $1 \n \033[0m"
}

#系统判断
os_type() {
  if [ ! -f /etc/os-release ]; then
    echo "other"
    return 1
  fi

  # 获取ID和ID_LIKE（去除引号）
  local os_id os_like
  os_id=$(grep '^ID=' /etc/os-release | cut -d= -f2 | tr -d '"')
  os_like=$(grep '^ID_LIKE=' /etc/os-release | cut -d= -f2 | tr -d '"')

  # 主判断逻辑
  if [[ "$os_id" == "centos" || "$os_id" == "rhel" || "$os_id" == "almalinux" || "$os_id" == "rocky" || "$os_id" == "ol" ]]; then
    echo "rhel" # 统一返回RHEL兼容系
  elif [[ "$os_id" == "ubuntu" ]]; then
    echo "ubuntu"
  elif [[ "$os_id" == "debian" ]]; then
    echo "debian"
  elif [[ "$os_id" == "opensuse-leap" || "$os_id" == "sles" ]]; then
    echo "suse"
  else
    # 处理衍生版（通过ID_LIKE判断）
    if [[ "$os_like" == *"rhel"* || "$os_like" == *"centos"* || "$os_like" == *"fedora"* ]]; then
      echo "rhel"
    elif [[ "$os_like" == *"suse"* ]]; then
      echo "suse"
    elif [[ "$os_like" == *"debian"* ]]; then
      echo "debian"
    else
      echo "other"
    fi
  fi
}

#判断root用户
if [[ $EUID -ne 0 ]]; then
  error_print "------ this script must be run as root ------"
  exit 1
fi

#判断系统架构
if [[ "$(uname -m)" != "x86_64" ]]; then
    error_print "------ we only support x86_64 architecture currently ------"
    exit 1
fi

normal_print "------ update host system ------"

os=$(os_type) || {
  error_print "failed to detect OS type"
  exit 1
}

#安装git和curl
if [ "${os}" = 'ubuntu' ] || [ "${os}" = 'debian' ]; then
  apt-get update
  apt-get install -y curl git
elif [ "${os}" = 'rhel' ]; then
  if [ -z "$(command -v dnf)" ]; then
    yum update
    yum install -y curl git
  else
    dnf update
    dnf install -y curl git
  fi
elif [ "${os}" = 'suse' ]; then
  zypper refresh
  zypper install -y curl git
else
  error_print "unsupported OS: ${os} (we only support ubuntu|debian|rhel|suse)"
  exit 1
fi

if [ ! -e ${ctc_docker_tar} ]; then
  error_print "------ ctc-docker.tar.gz not found ------"
  exit 1
fi

normal_print "------ extract ctc-docker.tar.gz ------"

#解压ctc-docker.tar.gz
cd ${base_dir} && tar -xzf ${site_name}.tar.gz

#忽略文件模式（权限）变更
git config --global core.fileMode false

#加入安全目录
git config --global --add safe.directory ${ctc_html_dir}

normal_print "------ install docker ------"

#安装docker
if [ -z "$(command -v docker)" ]; then
  bash ${ctc_docker_dir}/get-docker.sh --mirror Aliyun
fi

if [ -z "$(command -v docker)" ]; then
  error_print "------ docker command not found, please try again ------"
  exit 1
fi

if [ ! -d '/etc/docker' ]; then
  mkdir -p '/etc/docker'
fi

#docker镜像加速
if [ ! -e '/etc/docker/daemon.json' ]; then
  tee -a /etc/docker/daemon.json <<-EOF
{
  "registry-mirrors": [
    "https://mirror.ccs.tencentyun.com"
  ],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "500m",
    "max-file": "3"
  }
}
EOF
  systemctl daemon-reload
  systemctl restart docker
  chmod 666 /var/run/docker.sock
fi

normal_print "------ install docker-compose ------"

docker_compose_url="https://download.koogua.com/docker-compose-linux-x86_64"

#安装docker-compose
if [ -z "$(command -v docker-compose)" ]; then
  curl --retry 3 --retry-delay 5 --retry-max-time 30 "${docker_compose_url}" -o /usr/local/bin/docker-compose
  chmod +x /usr/local/bin/docker-compose
fi

if [ -z "$(command -v docker-compose)" ]; then
  error_print "------ docker-compose command not found, please try again ------"
  exit 1
fi

#切换目录
cd ${ctc_docker_dir} || exit

normal_print "------ build docker images ------"

docker-compose up -d

docker_ps=$(docker ps)

if [[ "${docker_ps}" =~ 'nginx' ]]; then
  success_print "------ nginx service ok ------"
else
  error_print "------ nginx service failed ------"
fi

if [[ "${docker_ps}" =~ 'php' ]]; then
  success_print "------ php service ok ------"
else
  error_print "------ php service failed ------"
fi

if [[ "${docker_ps}" =~ 'mysql' ]]; then
  success_print "------ mysql service ok ------"
else
  error_print "------ mysql service failed ------"
fi

if [[ "${docker_ps}" =~ 'redis' ]]; then
  success_print "------ redis service ok ------"
else
  error_print "------ redis service failed ------"
fi

if [[ "${docker_ps}" =~ 'xunsearch' ]]; then
  success_print "------ xunsearch service ok ------"
else
  error_print "------ xunsearch service failed ------"
fi
